package com.lxl.bt.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.constant.Type;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.leo.result.helper.ResultHelper;
import com.lxl.bt.R;
import com.lxl.bt.bean.FileBackBean;
import com.lxl.bt.net.NetApi;
import com.lxl.bt.net.Result;
import com.lxl.bt.retorfit.NetCallback;
import com.lxl.bt.retorfit.RetrofitUtil;
import com.lxl.bt.util.ACache;
import com.lxl.bt.util.GlideEngine;
import com.lxl.bt.util.GlideUtils;
import com.lxl.bt.util.MyUtils;
import com.lxl.bt.util.PicSelect;
import com.yanzhenjie.sofia.Sofia;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Create by lvxinlong
 * on  实名认证
 * on  2021年3月5日22:21:43
 **/
public class ShiMinRenZhenActivity extends BaseActivity {


    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.rlBack)
    RelativeLayout rlBack;
    @BindView(R.id.txt_toolbar_title)
    TextView txtToolbarTitle;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.tvRight)
    TextView tvRight;
    @BindView(R.id.rlRight)
    RelativeLayout rlRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.etName)
    EditText etName;
    @BindView(R.id.etSfz)
    EditText etSfz;
    @BindView(R.id.tvCommit)
    TextView tvCommit;
    @BindView(R.id.ivPhoto)
    ImageView ivPhoto;
    @BindView(R.id.ivVideo)
    ImageView ivVideo;
    private Context context;
    ACache aCache;
    private PicSelect pointerIconCompat;
    private int type;
    String cardurl,videourl;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shiminrenzhen);
        ButterKnife.bind(this);
        //状态栏全透明全屏显示页面，布局能够延伸到状态栏和导航栏下方
        Sofia.with(this)
                .invasionStatusBar()
                .statusBarLightFont()
//                .statusBarDarkFont()
                .statusBarBackgroundAlpha(0)
                .invasionNavigationBar()
                .navigationBarBackgroundAlpha(0);

        context = this;
        pointerIconCompat = new PicSelect(ShiMinRenZhenActivity.this);
        rlBack.setVisibility(View.VISIBLE);
        txtToolbarTitle.setText("实名认证");
        aCache = ACache.get(this);
    }

  public void select(){
      ResultHelper.with(ShiMinRenZhenActivity.this).requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, isGrant -> {
          if (isGrant) {
              if(type==1){
                  EasyPhotos.createAlbum(this, true, false, GlideEngine.getInstance())
                          .setFileProviderAuthority("com.huantansheng.easyphotos.demo.fileprovider")
                          .start(101);//也可以选择链式调用写法
              }else{
                  EasyPhotos.createAlbum(this, true, true, GlideEngine.getInstance())
                          .setFileProviderAuthority("com.huantansheng.easyphotos.demo.fileprovider")
                          .setCount(9)
                          .filter(Type.VIDEO)
                          .start(101);
              }

          } else {
              MyUtils.shortToastMsg(ShiMinRenZhenActivity.this, " 权限受限部分功能无法使用");
          }
      });
  }
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (resultCode == RESULT_OK) {
//            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
//                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
//                LocalMedia localMedia = selectList.get(0);
//                if (localMedia.isCompressed()) {
//                    String compressPath = localMedia.getCompressPath();
//                    setHeadPortrait(compressPath);
//                }
//
//
//            }
//        }
//        super.onActivityResult(requestCode, resultCode, data);
//    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            //相机或相册回调
            if (requestCode == 101) {
                //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
                ArrayList<Photo> resultPhotos =
                        data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                setHeadPortrait(resultPhotos.get(0).path);

                return;
            }




        } else if (RESULT_CANCELED == resultCode) {
            Toast.makeText(getApplicationContext(), "cancel", Toast.LENGTH_SHORT).show();
        }
    }




    public static Bitmap getNetVideoBitmap(String videoUrls) {
        Bitmap bitmap = null;

        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //根据url获取缩略图
            retriever.setDataSource(videoUrls, new HashMap());
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }


    private void setHeadPortrait(String compressPath) {
        Log.w("lxl", ">>" + compressPath);

//        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part  和后端约定好Key，这里的partName是用image
//        MultipartBody.Part body = MultipartBody.Part.createFormData("file", "file" + System.currentTimeMillis() + ".jpg", requestFile);
//        RequestBody cardNumber = RequestBody.create(MediaType.parse("multipart/form-data"), Prefs.getStringValue(com.lxl.bt.Constant.VirtualCardNumber));


        File file = new File(compressPath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);



        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .aliOssContent(body).enqueue(new NetCallback<Result<FileBackBean>>() {
            @Override
            public void onSuccess(Result<FileBackBean> result) {
                if (result.isSuccess()) {
                     if(type==1){
                         cardurl=result.getData().getData().get(0);
                         GlideUtils.loadImage(ivPhoto,result.getData().getData().get(0));
                     }else{
                         videourl=result.getData().getData().get(0);
                         ivVideo.setImageBitmap(getNetVideoBitmap(result.getData().getData().get(0)));
                     }

                }

            }

            @Override
            public void netLogin() {
            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);
            }

        });
    }



    @OnClick({R.id.rlBack, R.id.ivPhoto, R.id.ivVideo, R.id.tvCommit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlBack:
                finish();
                break;
            case R.id.ivPhoto:
                type=1;
                select();
                break;
            case R.id.ivVideo:
                type=2;
                select();
                break;
            case R.id.tvCommit:
                commit();
                break;
        }
    }

    private void commit() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .userValid(etSfz.getText().toString(),etName.getText().toString(),videourl,cardurl).enqueue(new NetCallback<Result<String>>() {
            @Override
            public void onSuccess(Result<String> result) {
                if (result.isSuccess()) {
                 MyUtils.shortToastMsg(ShiMinRenZhenActivity.this,result.getData());
                 finish();
                }
            }

            @Override
            public void netLogin() {

            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);

            }

        });
    }
}
